/**
 * 
 */
package de.guidoludwig.jtm.hibernate;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;

import de.guidoludwig.jtm.domain.FuzzyDate;

/**
 * @author guido
 *
 */
public class FuzzyDateUserType extends AbstractUserType {

	private static final int[] sqlTypes = {Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
	
	@Override
	public Object nullSafeGet(ResultSet resultSet, String[] name,
			SessionImplementor arg2, Object arg3) throws HibernateException,
			SQLException {
		String year = resultSet.getString(name[0]);
		String month = resultSet.getString(name[1]);
		String day = resultSet.getString(name[2]);
		FuzzyDate d = new FuzzyDate(year + "-" + month + "-" + day);
		return d;
	}

	@Override
	public void nullSafeSet(PreparedStatement resultSet, Object object, int index,
			SessionImplementor arg3) throws HibernateException, SQLException {
		if (object == null) {
			resultSet.setNull(index, Types.VARCHAR);
			resultSet.setNull(index+1, Types.VARCHAR);
			resultSet.setNull(index+2, Types.VARCHAR);
		} else {
			FuzzyDate fuzzyDate = (FuzzyDate)object;
			resultSet.setString(index, fuzzyDate.getYear());
			resultSet.setString(index+1, fuzzyDate.getMonth());
			resultSet.setString(index+2, fuzzyDate.getDay());
		}
	}

	@Override
	public Class<?> returnedClass() {
		return FuzzyDate.class;
	}

	@Override
	public int[] sqlTypes() {
		return sqlTypes;
	}

}
